package cn.liontalk.concurrent.readwritelock;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.IntStream;

public class LockExample {

    String myName;
    ReentrantLock lock = new ReentrantLock();
    ReentrantReadWriteLock reentrantReadWriteLock  = new ReentrantReadWriteLock();
 ReentrantReadWriteLock.WriteLock writeLock = null;

    public void printMyName() {
        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + "My name is " + myName);
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void setMyName() {
        lock.lock();

        try {
            myName=Thread.currentThread().getName();
            System.out.println(Thread.currentThread().getName() + "set my name to " + myName);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Long startTime = new Date().getTime();
        LockExample example = new LockExample();

        new Thread(()->{
            while (true){
                example.setMyName();

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(()->{
            while (true){

                example.setMyName();

                try {
                    Thread.sleep(new Random().nextInt(10));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        IntStream.range(0,100).forEach(num->{
            new Thread(()->{
                example.printMyName();
                System.out.println("NO. "+num+" reader finished. Time passed: "+(new Date().getTime()-startTime));
            }).start();
        });
    }
}
